package com.qianbao.qianbaobusiness.ui.support.businessanalysis;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baseandroid.config.Api;
import com.baseandroid.config.Global;
import com.baseandroid.event.SwitchAnalysisShopEvent;
import com.baseandroid.mvp.BaseMvpActivity;
import com.baseandroid.utils.MoneyUtil;
import com.baseandroid.utils.TimeUtils;
import com.qianbao.qianbaobusiness.R;
import com.qianbao.qianbaobusiness.json.BusinessAnalysisBean;
import com.qianbao.qianbaobusiness.json.MerchantInfo;
import com.qianbao.qianbaobusiness.json.ShopListInfo;
import com.qianbao.qianbaobusiness.ui.support.businessanalysis.switchshop.AnalysisSwitchShopActivity;
import com.qianbao.qianbaobusiness.ui.webview.SimpleWebViewActivity;
import com.qianbao.qianbaobusiness.ui.widget.RouteeFormView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author: Routee
 * @date 2018/6/13
 * @mail wangc4@qianbaocard.com
 * ------------1.本类由Routee开发,阅读、修改时请勿随意修改代码排版格式后提交到git。
 * ------------2.阅读本类时，发现不合理请及时指正.
 * ------------3.如需在本类内部进行修改,请先联系Routee,若未经同意修改此类后造成损失本人概不负责。
 */
public class BusinessAnalysisActivity extends BaseMvpActivity<BusinessAnalysisView, BusinessAnalysisPresenter> implements BusinessAnalysisView, RouteeFormView.DataChangeListener {

    @BindView(R.id.tv_title)
    TextView       mTvTitle;
    @BindView(R.id.tv_shop_name)
    TextView       mTvShopName;
    @BindView(R.id.tv_shop_count)
    TextView       mTvShopCount;
    @BindView(R.id.tv_select_store)
    TextView       mTvSelectStore;
    @BindView(R.id.ll_shop_selector)
    LinearLayout   mLlShopSelector;
    @BindView(R.id.tv_business_date)
    TextView       mTvBusinessDate;
    @BindView(R.id.tv_total_cash)
    TextView       mTvTotalCash;
    @BindView(R.id.tv_total_count)
    TextView       mTvTotalCount;
    @BindView(R.id.tv_yesterday_cash)
    TextView       mTvYesterdayCash;
    @BindView(R.id.tv_yesterday_count)
    TextView       mTvYesterdayCount;
    @BindView(R.id.tv_cashier_today_cash)
    TextView       mTvCashierTodayCash;
    @BindView(R.id.cashier_total_size)
    TextView       mTvCashierTotalSize;
    @BindView(R.id.tv_cashier_today_cash_compare_yesterday)
    TextView       mTvCashierTodayCashCompareYesterday;
    @BindView(R.id.tv_cashier_today_count)
    TextView       mTvCashierTodayCount;
    @BindView(R.id.cashier_today_size)
    TextView       mTvCashierTodaySize;
    @BindView(R.id.tv_cashier_today_count_compare_yesterday)
    TextView       mTvCashierTodayCountCompareYesterday;
    @BindView(R.id.tv_cashier_today_price)
    TextView       mTvCashierTodayPrice;
    @BindView(R.id.cashier_perprice_size)
    TextView       mTvCashierPerpriceSize;
    @BindView(R.id.tv_cashier_today_price_compare_yesterday)
    TextView       mTvCashierTodayPriceCompareYesterday;
    @BindView(R.id.tv_analysis_time)
    TextView       mTvAnalysisTime;
    @BindView(R.id.rfv)
    RouteeFormView mRfv;
    private Drawable             mIncreaseDrawable;
    private Drawable             mDecreaseDrawable;
    private BusinessAnalysisBean mBean;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_business_analysis;
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected void setupView() {
        mIncreaseDrawable = ContextCompat.getDrawable(this, R.drawable.icon_increase);
        mDecreaseDrawable = ContextCompat.getDrawable(this, R.drawable.icon_decrease);
        mIncreaseDrawable.setBounds(0, 0, mIncreaseDrawable.getMinimumWidth(), mIncreaseDrawable.getMinimumHeight());
        mDecreaseDrawable.setBounds(0, 0, mDecreaseDrawable.getMinimumWidth(), mDecreaseDrawable.getMinimumHeight());
        mTvTitle.setText("经营分析");
        initStores();
        initStoreName();
        initData();
    }

    private void initData() {
        getPresenter().getManagerStatics(getMerchantNo());
    }

    private void initStores() {
        ShopListInfo shopListInfo = Global.getShopListInfo();
        ShopListInfo selectedShopListInfo = Global.getSelectedAnalysisShopListInfo();
        int count = 0;
        if (shopListInfo.merchantList.size() <= 1) {
            if (shopListInfo.merchantList.size() == 0) {
                Global.setSelectedAnalysisShopListInfo(new ShopListInfo());
                return;
            }
            shopListInfo.merchantList.get(0).isSelected = true;
            Global.setSelectedAnalysisShopListInfo(shopListInfo);
            return;
        } else {
            for (MerchantInfo merchantInfo : shopListInfo.merchantList) {
                for (MerchantInfo selectedInfo : selectedShopListInfo.merchantList) {
                    if (merchantInfo.merchantNo.equals(selectedInfo.merchantNo)) {
                        merchantInfo.isSelected = selectedInfo.isSelected;
                        if (selectedInfo.isSelected) {
                            count++;
                        }
                    }
                }
            }
            if (count == 0) {
                shopListInfo.merchantList.get(0).isSelected = true;
            }
            Global.setSelectedAnalysisShopListInfo(shopListInfo);
        }
    }

    private void initStoreName() {
        StringBuilder sb = new StringBuilder();
        ShopListInfo selectedShopListInfo = Global.getSelectedAnalysisShopListInfo();
        if (selectedShopListInfo.merchantList.size() <= 1) {
            mLlShopSelector.setVisibility(View.GONE);
            return;
        }
        mLlShopSelector.setVisibility(View.VISIBLE);
        int count = 0;
        for (MerchantInfo merchantInfo : selectedShopListInfo.merchantList) {
            if (merchantInfo.isSelected) {
                sb.append(merchantInfo.merchantName).append(",");
                count++;
            }
        }
        if (count == selectedShopListInfo.merchantList.size()) {
            mTvShopName.setText("已选全部门店");
            mTvShopCount.setText("");
            return;
        }
        String name = sb.substring(0, sb.lastIndexOf(","));
        mTvShopName.setText(name);
        if (count > 1) {
            mTvShopCount.setText("共" + count + "家店");
        } else {
            mTvShopCount.setText("");
        }
    }

    private String getMerchantNo() {
        ShopListInfo infos = Global.getSelectedAnalysisShopListInfo();
        StringBuilder sb = new StringBuilder();
        for (MerchantInfo merchantInfo : infos.merchantList) {
            if (merchantInfo.isSelected) {
                sb.append(merchantInfo.merchantNo).append(",");
            }
        }
        String merchantNos = "";
        if (!TextUtils.isEmpty(sb)) {
            merchantNos = sb.substring(0, sb.lastIndexOf(","));
        }
        return merchantNos == null ? "" : merchantNos;
    }

    private String getMerchantNames() {
        ShopListInfo infos = Global.getSelectedAnalysisShopListInfo();
        StringBuilder sb = new StringBuilder();
        for (MerchantInfo merchantInfo : infos.merchantList) {
            if (merchantInfo.isSelected) {
                sb.append(merchantInfo.merchantName).append(",");
            }
        }
        String merchantNames = sb.substring(0, sb.lastIndexOf(","));
        return merchantNames == null ? "" : merchantNames;
    }

    @Override
    protected void setupData(Bundle savedInstanceState) {

    }

    @OnClick({R.id.iv_back_toolbar, R.id.ll_shop_selector, R.id.tv_cashier_analysis_more})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back_toolbar:
                finish();
                break;
            case R.id.ll_shop_selector:
                Intent switchShopIntent = new Intent(this, AnalysisSwitchShopActivity.class);
                startActivity(switchShopIntent);
                break;
            case R.id.tv_cashier_analysis_more:
                Intent cashierIntent = new Intent(this, SimpleWebViewActivity.class);
                cashierIntent.putExtra("webview_url", Api.getBussinessUrl("cashAnalysis", getMerchantNo(), getMerchantNames()));
                startActivity(cashierIntent);
                break;
            default:
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(SwitchAnalysisShopEvent event) {
        initStoreName();
        initData();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onError() {

    }

    @Override
    public void getManagerStaticsSuccess(BusinessAnalysisBean bean) {
        //经营概况
        mTvTotalCash.setText(MoneyUtil.parseMoneyWithComma(bean.getData().getManageSummary().getCashTotalAmt()));
        mTvTotalCount.setText(MoneyUtil.parseMoneyWithComma(bean.getData().getManageSummary().getCashTotalNum()) + "笔");
        mTvYesterdayCash.setText(MoneyUtil.parseMoneyWithComma(bean.getData().getManageSummary().getCashAmt1()));
        mTvYesterdayCount.setText(MoneyUtil.parseMoneyWithComma(bean.getData().getManageSummary().getCashNum1()) + "笔");

        //今日收银分析
        mTvCashierTodayCash.setText(MoneyUtil.parseMoneyWithComma(bean.getData().getCashSummary().getCashAmt0()));
        setCrease(mTvCashierTotalSize, mTvCashierTodayCashCompareYesterday, bean.getData().getCashSummary().getCashAmtPer0());
        mTvCashierTodayCount.setText(MoneyUtil.parseMoneyWithComma(bean.getData().getCashSummary().getCashNum0()));
        setCrease(mTvCashierTodaySize, mTvCashierTodayCountCompareYesterday, bean.getData().getCashSummary().getCashNumPer0());
        mTvCashierTodayPrice.setText(MoneyUtil.parseMoneyWithComma(bean.getData().getCashSummary().getAvgAmt0()));
        setCrease(mTvCashierPerpriceSize, mTvCashierTodayPriceCompareYesterday, bean.getData().getCashSummary().getAvgAmtPer0());

        mTvBusinessDate.setText("数据更新于 " + TimeUtils.getDateNDaysDelay(-1, "yyyy-MM-dd"));
        mTvAnalysisTime.setText("数据更新于 " + TimeUtils.getNowDate("HH:mm:ss", 0));

        initFormView(bean);
    }

    private void initFormView(BusinessAnalysisBean bean) {
        mBean = bean;
        Map<Integer, List<RouteeFormView.Units>> map = new LinkedHashMap<>();
        List<BusinessAnalysisBean.DataBean.CashSummaryBean.ListBean> list = bean.getData().getCashSummary().getList();
        ArrayList<RouteeFormView.Units> units = new ArrayList<>();
        for (BusinessAnalysisBean.DataBean.CashSummaryBean.ListBean data : list) {
            units.add(new RouteeFormView.Units(Double.parseDouble(data.getTradeAmt()), Integer.parseInt(data.getXDate()) + 1 + ""));
        }
        units.add(0, new RouteeFormView.Units(0, "0"));
        map.put(Color.parseColor("#FFB3B3"), units);
        mRfv.resetData(map);
        mRfv.setOnHelpDataChangedListener(this);
    }

    private void setCrease(TextView preview, TextView view, String per) {
        if (per == null) {
            return;
        }
        if (per.contains("-")) {
            view.setVisibility(View.VISIBLE);
            preview.setText("较昨天");
            view.setTextColor(ContextCompat.getColor(this, R.color.business_green));
            view.setText(per);
            view.setCompoundDrawables(null, null, mDecreaseDrawable, null);
        } else if (per.contains("#")) {
            view.setVisibility(View.GONE);
            preview.setText("昨天数据为0");
        } else {
            view.setVisibility(View.VISIBLE);
            preview.setText("较昨天");
            view.setTextColor(ContextCompat.getColor(this, R.color.text_red));
            view.setText(per);
            view.setCompoundDrawables(null, null, mIncreaseDrawable, null);
        }
    }

    @Override
    public void dataChanged(int color, int position) {
        position = position - 1;
        List<BusinessAnalysisBean.DataBean.CashSummaryBean.ListBean> list = mBean.getData().getCashSummary().getList();
        List<List<RouteeFormView.TextUnit>> textUnits = new ArrayList<>();
        if (position == -1) {
            List<RouteeFormView.TextUnit> line1 = new ArrayList<>();
            line1.add(new RouteeFormView.TextUnit(Color.parseColor("#999999"), "0"));
            textUnits.add(line1);

            List<RouteeFormView.TextUnit> line2 = new ArrayList<>();
            line2.add(new RouteeFormView.TextUnit(Color.parseColor("#434343"), "收银：" + "0"));
            line2.add(new RouteeFormView.TextUnit(Color.parseColor("#999999"), " 元"));
            textUnits.add(line2);

            List<RouteeFormView.TextUnit> line3 = new ArrayList<>();
            line3.add(new RouteeFormView.TextUnit(Color.parseColor("#434343"), "消费：" + "0"));
            line3.add(new RouteeFormView.TextUnit(Color.parseColor("#999999"), " 元"));
            textUnits.add(line3);

            List<RouteeFormView.TextUnit> line4 = new ArrayList<>();
            line4.add(new RouteeFormView.TextUnit(Color.parseColor("#434343"), "笔数：" + "0"));
            line4.add(new RouteeFormView.TextUnit(Color.parseColor("#999999"), " 笔"));
            textUnits.add(line4);
        } else {
            List<RouteeFormView.TextUnit> line1 = new ArrayList<>();
            line1.add(new RouteeFormView.TextUnit(Color.parseColor("#999999"), list.get(position).getDate()));
            textUnits.add(line1);

            List<RouteeFormView.TextUnit> line2 = new ArrayList<>();
            line2.add(new RouteeFormView.TextUnit(Color.parseColor("#434343"), "收银：" + MoneyUtil.parseMoneyWithComma(list.get(position).getTradeAmt())));
            line2.add(new RouteeFormView.TextUnit(Color.parseColor("#999999"), " 元"));
            textUnits.add(line2);

            List<RouteeFormView.TextUnit> line3 = new ArrayList<>();
            line3.add(new RouteeFormView.TextUnit(Color.parseColor("#434343"), "消费：" + MoneyUtil.parseMoneyWithComma(list.get(position).getOrderAmt())));
            line3.add(new RouteeFormView.TextUnit(Color.parseColor("#999999"), " 元"));
            textUnits.add(line3);

            List<RouteeFormView.TextUnit> line4 = new ArrayList<>();
            line4.add(new RouteeFormView.TextUnit(Color.parseColor("#434343"), "笔数：" + list.get(position).getNum()));
            line4.add(new RouteeFormView.TextUnit(Color.parseColor("#999999"), " 笔"));
            textUnits.add(line4);
        }
        mRfv.setHelpText(textUnits);
    }
}
